package com.resou.reader.bookdetail;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.AddShelfResultBean;
import com.resou.reader.api.entry.BaseComment;
import com.resou.reader.api.entry.BookDetailBean;
import com.resou.reader.api.entry.CommentBean;
import com.resou.reader.api.entry.CommonData;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.entry.TypeBean;
import com.resou.reader.api.service.BookService;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.bookdetail.comment.CommentListActivity;
import com.resou.reader.bookdetail.view.CatalogueActivity;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.bookshelf.readhistory.datasupport.DataSupport;
import com.resou.reader.bookshelf.readhistory.datasupport.ReaderHistory;
import com.resou.reader.data.Injection;
import com.resou.reader.data.bookdetail.BookDetailRepository;
import com.resou.reader.data.bookshelf.BookshelfRepository;
import com.resou.reader.data.bookshelf.BookshelfService;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.discovery.comment.CommentActivity;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.reader.v.ReaderActivity;
import com.resou.reader.utils.eventbus.LoadBookEvent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

import static com.resou.reader.commom.Constant.APP;

/**
 * 书详情的Presenter层
 */
public class BookDetailPresenter extends ResouBasePresenter<IBookDetailContract.IBookDetailView> implements IBookDetailContract.IBookDetailPresenter {
    private static final String TAG = BookDetailPresenter.class.getSimpleName();

    private BookService mService;
    private BookshelfService mBookshelfService;
    private BookDetailBean mBookDetailBean;// book信息
    private CommentBean mCommentBean;
    private List<TypeBean> mRecommendList = new ArrayList<>();//推荐集合
    private String bookId;
    private final BookshelfRepository mBookshelfRepository;
    private final BookDetailRepository mBookDetailRepository;

    public BookDetailPresenter(IBookDetailContract.IBookDetailView iBookDetailView, String bookId) {
        super(iBookDetailView);
        mView = iBookDetailView;
        this.bookId = bookId;
        mService = ApiImp.getInstance().getService(BookService.class);
        mBookshelfService = ApiImp.getInstance().getService(BookshelfService.class);
        mBookshelfRepository = Injection.provideBookshelfRepository();
        mBookDetailRepository = Injection.provideBookDetailRepository();
    }

    /**
     * 启动目录
     */
    public void startCatalogueActivity(Activity context) {
        if (mBookDetailBean != null)
            CatalogueActivity.startActivity(context, bookId, mBookDetailBean);
//            CatalogueActivity.startActivity(context, bookId, mBookDetailBean.getChapterNum(), mBookDetailBean.getNovelName()
//                    , mBookDetailBean.getShareUrl(), mBookDetailBean.getNovelDescription());
    }

    @Override
    public void init(String bookId) {
        this.bookId = bookId;
        getBookDetailAndCommentAndRecommend(bookId);
    }


    /**
     * 检查是否已经加入了书架
     */
    @Override
    public void checkWhetherCollection() {
        mBookshelfService.checkIsCollected(bookId, UserInstance.getToken())
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<Integer>>() {
                    @Override
                    public void accept(Result<Integer> result) throws Exception {
                        if (result.getData() != null && (result.getData() == 1)) {
                            mView.refreshAddToShelfBtn(true);
                        } else {
                            mView.refreshAddToShelfBtn(false);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mView.refreshAddToShelfBtn(false);
                    }
                });
    }

    /**
     * 获取详情页加载需要的 书籍基本信息、ic_comment_write、推荐(三合一 卧槽)
     */
    @Override
    public void getBookDetailAndCommentAndRecommend(String bookId) {
        mView.showProgress();
        String token = UserInstance.isLogin() ? UserInstance.getToken() : null;
        //                            RsLog.d("getBookDetailAndCommentAndRecommend  error!" + throwable.getMessage());
        addCompositeDisposable(
                Observable.zip(mService.getBookDetail(token, bookId, APP, null).subscribeOn(Schedulers.io())
                        , mService.reviewComment(bookId, "2", 0, 10).subscribeOn(Schedulers.io())
                        , mService.typeList(bookId).subscribeOn(Schedulers.io())
                        , (commonDataResult, listResult, result) -> {
                            List<Object> list = new ArrayList<>();
                            //add book信息
                            if (commonDataResult.getData() != null) {
                                mBookDetailBean = commonDataResult.getData().getData();
                                list.add(mBookDetailBean);
                            } else {
                                list.add(null);
                            }
                            // add ic_comment_write
                            mCommentBean = null;
                            if (listResult.getData() != null && listResult.getData().size() > 0) {
                                BaseComment commentBeans = listResult;
                                list.add(commentBeans);
                            } else {
                                list.add(null);
                            }

                            //add 推荐书籍
                            if (result.getData() != null && result.getData() != null && result.getData().size() > 0) {
                                List<TypeBean> srcRecommends = result.getData();
                                mRecommendList.clear();
                                for (int i = 0; i < srcRecommends.size(); i++) {
                                    TypeBean bean = srcRecommends.get(i);
                                    mRecommendList.add(bean);
                                }
                                Log.i(TAG, "getBookDetailAndCommentAndRecommend: " + mRecommendList.size());
                                list.add(mRecommendList);
                            } else {
                                list.add(null);
                            }
                            return list;
                        }).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(objects -> {
                            mView.initViewData(objects);
                            mView.showContent();
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                mView.showError(throwable);
                            }
                        })
        );
    }

    /**
     * 加入书架，存储在本地数据库
     */
    @Override
    public void addToBookShelf(String token) {
        if (mBookDetailBean != null) {
            //添加到本地书架
            DataSupport.getInstance().saveCollection(mBookDetailBean, "未读", "", 0, 0, 0);
            mView.refreshAddToShelfBtn(true);
            //添加到云端书架
            mBookshelfRepository.addToBookShelf(mBookDetailBean, token, APP)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DisposableObserver<Result<CommonData<AddShelfResultBean>>>() {

                        @Override
                        public void onNext(Result<CommonData<AddShelfResultBean>> commonDataResult) {

                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.d(TAG, "onError:网络 添加错误,错误信息:" + e.getMessage());
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    /**
     * 启动到书籍详情页
     */
    @Override
    public void startToBookDetail(int index) {
        TypeBean typeBean = mRecommendList.get(index);
//        RsLog.d("typeBean id " + typeBean.getId());
        BookDetailActivity.startDetailActivity(mView.getViewContext(), typeBean.getId() + "");
    }

    /**
     * 开始阅读
     */
    @Override
    public void startToReader(Activity activity) {
        if (mBookDetailBean == null)
            return;
        List<ReaderHistory> history = LitePal.select("bookId", "name", "author", "picUrl", "historyChapterId", "description"
                , "chapterIndex", "pageIndex", "charIndex", "userUpdateTime", "historyChapterName", "chapterSum", "zsBookId", "lastChapterName")
                .where("bookId = ?", String.valueOf(mBookDetailBean.getId())).find(ReaderHistory.class);
        if (history != null && history.size() > 0) {
            ReaderActivity.startActivity(mView.getViewContext(), history.get(0));
            return;
        }
        List<BookCollection> collection = LitePal.select("bookId", "name", "author", "picUrl", "historyChapterId", "description"
                , "chapterIndex", "pageIndex", "charIndex", "userUpdateTime", "historyChapterName", "chapterSum", "zsBookId", "lastChapterName")
                .where("bookId = ?", String.valueOf(mBookDetailBean.getId())).find(BookCollection.class);
        if (collection != null && collection.size() > 0) {
            ReaderActivity.startActivity(mView.getViewContext(), collection.get(0));
            return;
        }
        ReaderActivity.startActivity(activity, mBookDetailBean, false);
    }

    /**
     * 阅读最后一章
     */
    @Override
    public void startToReaderLastChapter(Activity activity) {
        ReaderActivity.startActivity(activity, mBookDetailBean, true);
    }

    /**
     * 分享
     */
    @Override
    public void share(Activity activity, UMShareListener shareListener) {
        if (mBookDetailBean == null)
            return;
        String shareUrl = mBookDetailBean.getShareUrl();
//        shareUrl = shareUrl.replace("bookDetails", "bookDetail").replace("testpc", "m");
        shareUrl = "http://share.resouxs.com/details.html?id=" + mBookDetailBean.getId() + "&app=app";
        UMWeb web = new UMWeb(shareUrl);
        web.setTitle("平台补贴，海量正版书籍免费看！");//标题
        web.setDescription("我正在看《" + mBookDetailBean.getNovelName() + "》" + mBookDetailBean.getNovelDescription() + "");
        web.setThumb(new UMImage(activity, mBookDetailBean.getCoverUrl()));
        new ShareAction(activity).withMedia(web).setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE).setCallback(shareListener).open();
    }

    /**
     * 点赞
     */
    @Override
    public void like() {
        addCompositeDisposable(
                mService.likeComment(UserInstance.getToken(), 0, mCommentBean.getId())
                        .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(result -> mView.refreshLike(mCommentBean.getPraisenum()),
                                Throwable::printStackTrace)
        );
    }

//    /**
//     * 写书评
//     *
//     * @param str 评论内容
//     */
//    @Override
//    public void publishComment(final Activity activity, String str) {
//        addCompositeDisposable(
//                mService.addComment(UserInstance.getToken(), str,
//                        String.valueOf(mBookDetailBean.getId()), null, "")
//                        .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(result -> {
//                            Toast.makeText(activity, "发表成功", Toast.LENGTH_SHORT).show();
//                            if (mCommentBean == null) {
//                                //这将是第一条评论，需要刷新BookDetail评论区
//                                mCommentBean = result.getData();
//                                List<Object> tempList = new ArrayList<>();
//                                tempList.add(mBookDetailBean);
//                                tempList.add(mCommentBean);
//                                tempList.add(mRecommendList);
////                                mView.refreshRecyclerItem(tempList, 1);
//                            }
//                        }, throwable -> {
//                        })
//        );
//    }

    //    推荐接口
    @Override
    public void getTypeList() {
        addCompositeDisposable(
                mService.typeList(bookId)
                        .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(result -> {
                            List<TypeBean> list = new ArrayList<>();
                            if (result.getData() != null && result.getData() != null && result.getData().size() > 0) {
                                List<TypeBean> srcRecommends = result.getData();
                                for (int i = 0; i < Math.min(8, srcRecommends.size()); i++) {
                                    TypeBean bean = srcRecommends.get(i);
                                    list.add(bean);
                                }
                            }
                            mView.refreshRecyclerItem(list);
                        }, throwable -> {
                            mView.showContent();
                        })
        );
    }

    //    评论接口
    @Override
    public void getCommentList() {
        mService.reviewComment(bookId, "2", 0, 10)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseComment>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(BaseComment baseComment) {
                        mView.refreshCommentItem(baseComment.getData(),
                                baseComment.getDataSize() + "");
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 启动评论页
     */
    @Override
    public void startComment() {
        CommentListActivity.start(mView.getViewContext(), bookId, mBookDetailBean.getNovelName());
    }

    @Override
    public void addToBookShelf2() {
        if (mBookDetailBean != null) {
            //添加到本地书架
            ReaderHistory readerHistory = LitePalHelper.loadReadHistory(mBookDetailBean.getId());
            if (readerHistory != null) {
//                bookCo.setPageIndex(readerHistory.getPageIndex());
//                bookCo.setCharIndex(readerHistory.getCharIndex());
//                bookCo.setChapterIndex(readerHistory.getChapterIndex());
//                bookCo.setHistoryChapterId(readerHistory.getHistoryChapterId());
                DataSupport.getInstance().saveCollection(mBookDetailBean, readerHistory.getHistoryChapterName(), readerHistory.getHistoryChapterId(), readerHistory.getChapterIndex(), readerHistory.getPageIndex(), readerHistory.getCharIndex());

            } else {
                DataSupport.getInstance().saveCollection(mBookDetailBean, "未读", "", 0, 0, 0);

            }
            mView.refreshAddToShelfBtn(true);

            //添加到云端书架
            if (UserInstance.isLogin()) {
                // 免费书是0，不免费的是1
                // 参数是由bookId加下滑线，加上0或者1组成的
                mBookshelfRepository.uploadBooks(UserInstance.getToken(), mBookDetailBean.getId() + "_1", "app")
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new DisposableObserver<Result>() {

                            @Override
                            public void onNext(Result result) {
                                EventBus.getDefault().post(new LoadBookEvent());
                            }

                            @Override
                            public void onError(Throwable e) {
                                EventBus.getDefault().post(new LoadBookEvent());
                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            } else {
                EventBus.getDefault().post(new LoadBookEvent());
            }
        }
    }

    public void onDestroy()
    {
        if (mRecommendList!= null) {
            mRecommendList.clear();
            mRecommendList = null;
        }
        if (mBookDetailBean!= null) {
            mBookDetailBean = null;
        }
        if (mCommentBean!= null) {
            mCommentBean = null;
        }
    }
}
